from django.contrib.auth.hashers import make_password

from employee.models import EmpDepartment
from utils.token import Token
from auther.models import AdminUser, AdminRoles
from xftinterfaces.models import XftAccount


# 创建用户
def create_user(username, password, account, is_superuser):
    return_data = {'code': "", "msg": ""}
    password_encrypt = make_password(password)
    # 判断账户是否存在
    judge_account = AdminUser.objects.filter(username=username)
    if judge_account.exists():
        return_data['code'] = 422
        return_data["msg"] = '用户已存在'
        return return_data
    else:
        AdminUser.objects.create(username=username, password=password_encrypt, account=account, is_superuser=is_superuser)
        return_data['code'] = 201
        return_data["msg"] = '创建用户成功'
        return return_data


def search_user(token):
    return_data = {'code': "", "msg": "", "data": {}}
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    user_info = AdminUser.objects.filter(id=user_id).values("is_superuser", "account", "avatar", "introduction", 'roles__role')
    if user_info.exists():
        return_data['code'] = 200
        return_data['msg'] = "获取用户信息成功"
        return_data['data']['roles'] = [role['roles__role'] for role in user_info]
        return_data['data']['name'] = user_info[0]['account']
        return_data['data']['avatar'] = user_info[0]['avatar']
        return_data['data']['introduction'] = user_info[0]['introduction']
    else:
        return_data['code'] = 500
        return_data['msg'] = "获取用户信息失败"
    return return_data


def user_list(token, name, page, limit):
    return_data = {'code': "", "msg": "", "data": {'datalist': []}}
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        kwargs = {}
        args = ()
        if name:
            kwargs["username__contains"] = name
        user_info = AdminUser.objects.filter(*args, **kwargs).values('id', "is_superuser", "is_used", "username", "account", "avatar", "introduction","xft_account_id")[(page - 1) * limit:limit * page]
        if user_info.exists():
            return_data['code'] = 200
            return_data['msg'] = "获取用户信息成功"
            return_data['data']['pageCount'] = AdminUser.objects.filter(*args, **kwargs).count()
            for data in user_info:
                return_data['data']['datalist'].append({
                    'id': data['id'],
                    'username': data['username'],
                    'is_superuser': data['is_superuser'],
                    'is_used': data['is_used'],
                    'account': data['account'],
                    'avatar': data['avatar'],
                    'introduction': data['introduction'],
                    'xft_id': data['xft_account_id'],
                })

        else:
            return_data['code'] = 500
            return_data['msg'] = "获取用户信息失败"
    return return_data


def permission_list(token, id):
    """
    获取所有权限列表和已有权限列表
    :param token:
    :return:
    """
    return_data = {'code': "", "msg": "", "data": {'permissionList': [], 'checkedList': [], 'userInfo': {}}}
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        # 获取所有权限
        permission_list = AdminRoles.objects.filter(is_used=True).order_by('parent_id').values('id', 'role_name', 'parent_id')
        if permission_list.exists():
            return_data['code'] = 200
            return_data['msg'] = '获取数据成功'
            for permission in permission_list:
                if permission['parent_id'] is None:
                    return_data['data']['permissionList'].append({
                        'id': permission['id'],
                        'label': permission['role_name'],
                        'children': []
                    })
                else:
                    for data in return_data['data']['permissionList']:
                        if data['id'] == permission['parent_id']:
                            data['children'].append({
                                'id': permission['id'],
                                'label': permission['role_name']
                            })
        # 获取已有权限
        if id == '':
            return_data['data']['checkedList'] = []
        else:
            user_permission_list = AdminUser.objects.filter(id=id).values('roles')
            if user_permission_list.exists():
                for user_p in user_permission_list:
                    return_data['data']['checkedList'].append(user_p['roles'])
        #  获取账户信息
        if id == '':
            return_data['data']['userInfo'] = {
                'username': '',
                'password': '',
                'account': '',
                'introduction': '',
                'is_superuser': False,
                'is_used': False,
            }
        else:
            user_info_list = AdminUser.objects.filter(id=id).values("is_superuser", "username", "password", "account", "introduction", "is_used","xft_account_id")
            if user_info_list.exists():
                return_data['data']['userInfo'] = {
                    'username': user_info_list[0]['username'],
                    'password': user_info_list[0]['password'],
                    'account': user_info_list[0]['account'],
                    'introduction': user_info_list[0]['introduction'],
                    'is_superuser': user_info_list[0]['is_superuser'],
                    'is_used': user_info_list[0]['is_used'],
                    'xft_id': user_info_list[0]['xft_account_id'],
                }
        return return_data


def get_trees(data,
              key_column='id',
              parent_column='parent_id',
              child_column='children',
              current_column=None,
              current_path=None):
    """
    :param data: 数据列表
    :param key_column: 主键字段，默认id
    :param parent_column: 父ID字段名，父ID默认从0开始
    :param child_column: 子列表字典名称
    :param current_column: 当前展开值字段名，若找到展开值增加['open'] = '1'
    :param current_path: 当前展开值
    :return: 树结构
    """
    data_dic = {}
    for d in data:
        data_dic[d.get(key_column)] = d  # 以自己的权限主键为键,以新构建的字典为值,构造新的字典

    data_tree_list = []  # 整个数据大列表
    for d_id, d_dic in data_dic.items():
        # print(d_id,d_dic)
        pid = d_dic.get(parent_column)  # 取每一个字典中的父id
        if pid == 0:  # 父id=0，就直接加入数据大列表
            data_tree_list.append(d_dic)
        else:  # 父id>0 就加入父id队对应的那个的节点列表
            try:  # 判断异常代表有子节点，增加子节点列表=[]
                data_dic[pid][child_column].append(d_dic)
            except KeyError:
                data_dic[pid][child_column] = []
                data_dic[pid][child_column].append(d_dic)

        # 展开节点
        if current_path:
            if current_path == d_dic.get(current_column):
                d_dic['open'] = 1
                while pid:
                    data_dic[pid]['open'] = 1
                    pid = data_dic[pid][parent_column]
    return data_tree_list


get_son_trees = []


def get_son_tree(data, target_id):
    for i in data:
        if i['oa_files_dept_id'] == target_id:
            get_son_trees.append(i)
        elif 'children' in i.keys():
            get_son_tree(i['children'], target_id)
    return get_son_trees


get_son_depts = []


def get_son_dept(data):
    for i in data:
        get_son_depts.append(i['oa_files_dept_id'])
        if 'children' in i.keys():
            get_son_dept(i['children'])
    return get_son_depts


def dept_list(token, id):
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    return_data = {'code': '', "msg": '', "data": {'dept_tree_list': [], 'dept_checked': []}}
    # 获取所有部门
    if user_id:
        try:
            get_son_trees.clear()
            # 生成部门树
            tree_code_cmp = EmpDepartment.objects.filter().extra(select={'label': 'department_name'}).values('id', 'label', 'parent_id', 'department_level').order_by('department_level')
            total_tree_data = get_trees(tree_code_cmp, 'id', 'parent_id')
            if len(total_tree_data) > 0:
                return_data['code'] = 200
                return_data['msg'] = '获取部门成功'
                return_data['data']['dept_tree_list'] = total_tree_data
        except Exception as e:
            print(e)
        #
        if id == '':
            return_data['data']['dept_checked'] = []
        else:
            dept_checked_list = AdminUser.objects.filter(id=id).values('department__id')
            if dept_checked_list.exists():
                for dept in dept_checked_list:
                    return_data['data']['dept_checked'].append(dept['department__id'])
    print(return_data)
    return return_data


def xft_list(token):
    return_data = {'code': '', 'msg': '', 'data': {'xft': []}}
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        xft_list = XftAccount.objects.all().values('id', 'xft_company')
        if xft_list.exists():
            return_data['code'] = 200
            return_data['msg'] = '获取薪福通账户成功'
            return_data['data']['xft'] = list(xft_list)
    return return_data


def save_user_info(token, userInfo, deptList, permissionList, xft_id):
    return_data = {'code': "", "msg": "", "data": []}
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        local_user = AdminUser.objects.filter(username=userInfo['username']).values('password')
        if local_user.exists():
            return_data['code'] = 200
            return_data['msg'] = '用户更新成功'
            AdminUser.objects.update_or_create(
                defaults={
                    'username': userInfo['username'],
                    'account': userInfo['account'],
                    'avatar': 'https://living.chentantec.cn:18000/static/pic.png',
                    'introduction': userInfo['introduction'],
                    'is_superuser': userInfo['is_superuser'],
                    'is_used': userInfo['is_used'],
                    'xft_account_id': xft_id
                },
                username=userInfo['username']
            )
            admin = AdminUser.objects.get(username=userInfo['username'])
            admin.roles.set(permissionList)
            admin.department.set(deptList)
        else:
            return_data['code'] = 200
            return_data['msg'] = '用户创建成功'
            AdminUser.objects.create(
                username=userInfo['username'],
                password=make_password('runergy666'),
                account=userInfo['account'],
                avatar='https://living.chentantec.cn:18000/static/pic.png',
                introduction=userInfo['introduction'],
                is_superuser=userInfo['is_superuser'],
                is_used=userInfo['is_used'],
                xft_account_id=xft_id
            )
            admin = AdminUser.objects.get(username=userInfo['username'])
            admin.roles.set(permissionList)
            admin.department.set(deptList)
    else:
        return_data['code'] = 500
        return_data['msg'] = 'token已过期'
    return return_data


def update_user_passwpord(token, password):
    return_data = {'code': "", "msg": "", "data": []}
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        return_data['code'] = 200
        return_data['msg'] = '密码修改成功！'
        AdminUser.objects.filter(id=user_id).update(password=make_password(password))
    else:
        return_data['code'] = 500
        return_data['msg'] = '用户还未注册！'
    return return_data
